<?php

namespace app\controllers;

use Yii;
use app\models\Article;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\Pagination;
use app\models\Article_tag;
use app\models\Users;
use app\models\ArticleRecommend;
use app\models\Comments;
use app\controllers\BaseController;

/**
 * ArticleController implements the CRUD actions for Article model.
 */
class ArticleController extends BaseController {

    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['create', 'update', 'delete'],
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * 最新文章
     * @return mixed
     */
    public function actionIndex() {
        //获取最新列表
        $query = Article::find()->where(['status' => '1']);
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        $article_list = $query->offset($pages->offset)
                ->limit($pages->limit)
                ->orderBy('id desc')
                ->all();

        return $this->render('index', ['article_list' => $article_list, 'pages' => $pages]);
    }

    /**
     * 热门文章
     * @return type
     */
    public function actionHot() {
        //获取最新列表
        $query = Article::find()->where(['status' => '1']);
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        $article_list = $query->offset($pages->offset)
                ->limit($pages->limit)
                ->orderBy('view desc')
                ->all();

        return $this->render('hot', ['article_list' => $article_list, 'pages' => $pages]);
    }

    /**
     * Displays a single Article model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        //1、获取问答信息
        $article = Article::findOne($id);
        if (!$article) {
            throw new NotFoundHttpException('你所请求的页面不存在.');
        }
        Article::view_add($id);
        //2、获取tag标签
        $tags = Article_tag::get_show_tags($id);
        //3、获取用户信息
        $author = Users::findOne($article['uid']);
        //4、获取评论信息
        $comments = Comments::find()->where(['type' => 'article', 'rid' => $id])->all();
        //5、评论form
        $model_comment = new Comments();
        //6、判断当前登陆用户是否已经评论
        $is_comment = false;
        if (Yii::$app->user) {
            $result = Comments::findOne(['type' => 'article', 'rid' => $id, 'uid' => Yii::$app->user->identity->id]);
            if ($result) {
                $is_comment = true;
            }
        }

        //数据组装
        $data = [
            'article' => $article,
            'tags' => $tags,
            'author' => $author,
            'comments' => $comments,
            'model_comment' => $model_comment,
            'is_comment' => $is_comment
        ];
        return $this->render('view', $data);
    }

    /**
     * Creates a new Article model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $post = Yii::$app->request->post();
        $model = new Article();
        $model_article_tag = new Article_tag();

        if ($model->load($post) && $model->save()) {
            //创建qa成功，添加tags
            $model_article_tag->save_tags($model, $post['Article']['tags']);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', ['model' => $model,]);
        }
    }

    /**
     * Updates an existing Article model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id) {
        //判断该用户是否具有该文章操作权限
        Article::check_access($id, Yii::$app->user->identity->id);

        $post = Yii::$app->request->post();
        $model = $this->findModel($id);
        //获取所有tags
        $model->tags = Article_tag::get_edit_tags($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            //编辑article成功，编辑tags
            $model_article_tag = new Article_tag();
            $model_article_tag->update_tag($model, $post['Qa']['tags']);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', ['model' => $model,]);
        }
    }

    /**
     * Deletes an existing Article model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id) {
        //判断该用户是否具有该文章操作权限
        Article::check_access($id, Yii::$app->user->identity->id);

        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Article model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Article the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = Article::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * 用户点赞
     */
    public function actionAdd($aid) {
        $uid = Yii::$app->user->identity->id;
        if (!$uid) {
            return $this->redirect('/user/login');
        }
        $result = ArticleRecommend::findOne(['aid' => $aid, 'uid' => $uid]);
        if ($result) {
            return $this->redirect('/site/message', ['message' => '你已经推荐过了!请不要重复推荐!']);
        } else {
            $recommend = new ArticleRecommend();
            $recommend->aid = $aid;
            $recommend->uid = $uid;
            $recommend->save();
            //return $this->redirect('/article/view', ['id' => $aid]);
        }
    }

}
